package com.yjd.comm.util;
import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class EncryptionUtils{

    private  static String AESTYPE = "AES/CBC/PKCS5Padding";
    /**
     * 加密明文
     * @param keyStr
     * @param plainText
     * @return
     * @throws Exception
     */
    public static String encrypt(String keyStr, String plainText) throws Exception {
            Cipher cipher = Cipher.getInstance(AESTYPE);
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = plainText.getBytes("utf-8");
            byte[] plaintext = new byte[dataBytes.length];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keyspec = new SecretKeySpec(keyStr.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(keyStr.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return new String(Base64.encodeBase64(encrypted), "UTF-8");
    }

    /**
     * 解密密文
     * @param keyStr
     * @param encryptData
     * @return
     * @throws Exception
     */
    public static String desEncrypt(String keyStr,String encryptData) throws Exception {
            Cipher cipher = Cipher.getInstance(AESTYPE);
            SecretKeySpec keyspec = new SecretKeySpec(keyStr.getBytes(), "AES");
            IvParameterSpec ivspec = new IvParameterSpec(keyStr.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
            byte[] original = cipher.doFinal(Base64.decodeBase64(encryptData.getBytes("UTF-8")));
            return new String(original, "utf-8");

    }

    /**
     *  将密文信息转化为java对象
     * @param keyStr
     * @param encryptData
     * @param cs
     * @param <T>
     * @return
     * @throws Exception
     */
    public static  <T extends Object> T getEncryptModel(String keyStr,String encryptData,Class<T> cs)throws Exception {
        String obj = desEncrypt(keyStr,encryptData);
        if(obj!=null){
            JSON.parseObject(obj.toString(), cs);
        }
        return  null;
    }

    public static void main(String args[]) throws Exception {
        System.out.println(encrypt("1234567812345678","15800926537"));
       System.out.println(desEncrypt("1234567812345678","NUeqgGXBZvPl1I7+KIfeyQ=="));
    }
}